package com.fiveone.myapplication;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;


import java.util.Calendar;

public class MainActivity2 extends AppCompatActivity {
    private TextView tvDateTime;
    private Button btnSelectDateTime;
    private int selectedYear;
    private int selectedMonth;
    private int selectedDayOfMonth;
    private int selectedHourOfDay;
    private int selectedMinute;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        tvDateTime = findViewById(R.id.tv_date_time);
        btnSelectDateTime = findViewById(R.id.btn_select_date_time);

        btnSelectDateTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerAndTimePicker();
            }
        });
    }

    private void showDatePickerAndTimePicker() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);

        DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                (view, year1, month1, dayOfMonth1) -> {
                    selectedYear = year1;
                    selectedMonth = month1;
                    selectedDayOfMonth = dayOfMonth1;
                    showTimePicker();
                }, year, month, dayOfMonth);
        datePickerDialog.show();
    }

    private void showTimePicker() {
        TimePickerDialog timePickerDialog = new TimePickerDialog(this,
                (view, hourOfDay, minute1) -> {
                    selectedHourOfDay = hourOfDay;
                    selectedMinute = minute1;
                    updateDateTimeText();
                }, selectedHourOfDay, selectedMinute, false);
        timePickerDialog.show();
    }

    private void updateDateTimeText() {
        String dateTimeDesc = String.format("%d年%d月%d日 %d时%d分",
                selectedYear, selectedMonth + 1, selectedDayOfMonth,
                selectedHourOfDay, selectedMinute);
        tvDateTime.setText(dateTimeDesc);

    }
}